package com.wnhz.work.yz.fragment.shoppingcard;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.MultipleSelectActivity;
import com.wnhz.work.yz.activity.SettleAccountsActivity;
import com.wnhz.work.yz.activity.ShoppingDetailsActivity;
import com.wnhz.work.yz.adapter.FitmentAdapter;
import com.wnhz.work.yz.bean.FitmentBean;
import com.wnhz.work.yz.bean.MessageBean2;
import com.wnhz.work.yz.bean.RecommendShoppingBean;
import com.wnhz.work.yz.utils.MyUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wnhz.work.yz.utils.Tag.MULTIPLESELECT;

/**
 * A simple {@link Fragment} subclass.
 * ---家具馆
 */
public class FitmentFragment extends Fragment implements View.OnClickListener {

    private BaseActivity activity;
    private ImageView allSelect_img;
    private List<RecommendShoppingBean> recommendShoppingBeens = new ArrayList<>();
    private RelativeLayout rl_shopping;
    private List<FitmentBean> beanList = new ArrayList<>();
    private String fee;
    private SwipeMenuListView swipe;
    private TextView tv_all_price;
    private FitmentAdapter mAdapter;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        activity = (BaseActivity) getActivity();
        EventBus.getDefault().register(this);
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        view = inflater.inflate(R.layout.fragment_fitment, container, false);
        return view;
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageBean2 event) {
        int numS = event.getNums();
        beanList.get(event.getIndex()).setNum(numS + "");
        isAllSelect();
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        tv_all_price = (TextView) view.findViewById(R.id.tv_all_price);
        rl_shopping = (RelativeLayout) view.findViewById(R.id.rl_shopping);
        allSelect_img = (ImageView) view.findViewById(R.id.allSelect_img);
        view.findViewById(R.id.qx).setOnClickListener(this);
        view.findViewById(R.id.rl_all_selector).setOnClickListener(this);
        view.findViewById(R.id.tv_true).setOnClickListener(this);
        swipe = (SwipeMenuListView) view.findViewById(R.id.collector_listview);
        swipe.setFlag(true);
        upload();
    }

    private void updelete(int index) {
        activity.showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartId", beanList.get(index).getCart_id());
        XUtil.Post(Url.IDCART_DELJJCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                activity.closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: aacartId= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        activity.MyToast(info);
                        upload();
                    } else {
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                activity.closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private static final String TAG = "FitmentFragment";

    public void upload() {
        if (MyApplication.getInstance().getUserBean() == null) {
            return;
        }

        activity.showDialog();
        Map<String, Object> map = new HashMap<>();
   //     map.put("skuId", MyApplication.getInstance().getUserBean().getToken());
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        XUtil.Post(Url.CART_GETJJCARTLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                activity.closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: cart= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    fee = jsonObject.optString("fee");
                    JSONArray jsonArray = jsonObject.optJSONArray("info");
                    beanList.clear();
                    if (res.equals("1")) {
                        beanList.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            FitmentBean bean = new FitmentBean();
                            Gson gson = new Gson();
                            bean = gson.fromJson(jsonArray.optString(i), FitmentBean.class);

                            beanList.add(bean);
                            if (beanList.size() == 0) {
                                rl_shopping.setVisibility(View.GONE);
                            } else {
                                rl_shopping.setVisibility(View.VISIBLE);
                            }
                            setData();
                        }

                        isAllSelect();
                    }else {
                        rl_shopping.setVisibility(View.GONE);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();

                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                activity.closeDialog();
                Log.i(TAG, "onError: cart= " + ex);
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void setData() {

        mAdapter = new FitmentAdapter(getActivity(), cartBeanClickLisener, beanList);
        swipe.setAdapter(mAdapter);
        isAllSelect();
        swipe.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                activity.showDialogv7("确定删除该件商品吗？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updelete(position);
                    }
                });
                return false;
            }
        });
        SwipeMenuCreator creater = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                //同理create删除item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                deleteItem.setWidth(dp2px(90));
                deleteItem.setTitle("删除");
                deleteItem.setTitleSize(18);
                deleteItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(deleteItem);
            }
        };
        swipe.setMenuCreator(creater);
        swipe.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {

                    case 0:
                        //删除的逻辑
                        activity.showDialogv7("确定删除该件商品吗？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updelete(position);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
                        break;

                    default:
                        break;
                }
                return false;
            }
        });


        mAdapter.notifyDataSetChanged();
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, activity.getResources().getDisplayMetrics());
    }

    private View.OnClickListener cartBeanClickLisener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            Log.e("----p" + position, "" + beanList.get(position).getNum());
            int num;
            switch (v.getId()) {

                case R.id.select://选择
                    position = (int) v.getTag();
                    beanList.get(position).setIsselect(!beanList.get(position).isselect());
                    ImageView se = (ImageView) v;
                    if (beanList.get(position).isselect()) {
                        se.setImageResource(R.mipmap.ic_choose_li);
                    } else {
                        se.setImageResource(R.mipmap.ic_choose_nor);
                    }
                    isAllSelect();
                    break;

                case R.id.reduce://减少
                    position = (int) v.getTag();
                    num = Integer.parseInt(beanList.get(position).getNum());
                    if (num > 1) {
                        num--;
                        beanList.get(position).setNum(num + "");
                    }
                    TextView text = (TextView) v.getTag(R.id.add111);
                    text.setText(beanList.get(position).getNum());
                    isAllSelect();
                    break;

                case R.id.ll_add://增加
                    position = (int) v.getTag();
                    num = Integer.parseInt(beanList.get(position).getNum());
                    if (num < Integer.parseInt(beanList.get(position).getStore())) {
                        num++;
                        beanList.get(position).setNum("" + num);
                    } else {
                        activity.MyToast("库存不足");
                    }
                    TextView text2 = (TextView) v.getTag(R.id.add111);
                    text2.setText(beanList.get(position).getNum());
                    isAllSelect();
                    break;

                case R.id.select_multiple:

                    ActivityCompat.startActivityForResult(getActivity(),
                            new Intent(getActivity(), MultipleSelectActivity.class).putExtra("from", "FitmentFragment"), MULTIPLESELECT, null);

                    break;
                case R.id.iv_all_choose:
                    quXiao();
                    break;
            }
        }
    };

    private void changeNum(int num, int position) {
        activity.showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartId", beanList.get(position).getCart_id());
        map.put("nums", num);
        System.out.println("ddddddddd     " + num);
        XUtil.Post(Url.CART_CHANGEJJCARTNUM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                activity.closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: nums= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        upload();
                    } else {
                        if ("商品库存不足！".equals(info))
                            activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                index++;
            }

            @Override
            public void onFinished() {
                if (index == beanList.size()) {
                    activity.closeDialog();
                    h.sendEmptyMessage(1);
                }
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                activity.closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ArrayList<FitmentBean> beanlist = new ArrayList<>();
            double allWeight = 0;
            for (int i = 0; i < beanList.size(); i++) {
                double weight = 0, num = 0;
                if (beanList.get(i).isselect()) {
                    if (MyUtils.isNumber(beanList.get(i).getWeight())) {
                        weight = Double.parseDouble(beanList.get(i).getWeight());
                    }
                    try {
                        num = Double.parseDouble(beanList.get(i).getNum());
                    } catch (Exception e) {
                        num = 0;
                    }
                    allWeight += weight * num;
                    beanlist.add(beanList.get(i));
                }
            }
            if (beanlist.size() > 0) {
                String allPrice = tv_all_price.getText().toString();
                Log.e("----allWeight", allWeight + "");
                startActivityForResult(new Intent(getActivity(), SettleAccountsActivity.class).putExtra("weight", allWeight)
                        .putExtra("bean", beanlist).putExtra("allPrice", allPrice), QUXIAO);
                return;
            } else {
                activity.MyToast("请选择购买商品");
            }
        }
    };

    private View.OnClickListener recommendShoppingBeanLisener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            switch (v.getId()) {
                case R.id.lay:
                    Intent intent = new Intent(getActivity(), ShoppingDetailsActivity.class);
                    intent.putExtra("goodsId", recommendShoppingBeens.get(position).getGoods_id());
                    startActivity(intent);
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case MULTIPLESELECT:
                break;
            case QUXIAO:
                quXiao();
                break;
        }
    }

    private boolean isAllSelect;
    public static final int QUXIAO = 100;
    private int index = 0;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.rl_all_selector:
            case R.id.qx:

                quXiao();
                break;
            //下单
            case R.id.tv_true:
                index = 0;
                activity.showDialog();
                new Thread() {
                    @Override
                    public void run() {
                        for (int i = 0; i < beanList.size(); i++) {
                            changeNum(Integer.parseInt(beanList.get(i).getNum()), i);
                        }
                        super.run();
                    }
                }.start();
                break;

            default:
                break;
        }
    }

    private void quXiao() {
        if (beanList.size() < 1) {
            allSelect_img.setImageResource(R.mipmap.ic_choose_nor);
            activity.MyToast("请先添加项目");
            return;
        }
        isAllSelect = !isAllSelect;
        if (isAllSelect) {
            allSelect_img.setImageResource(R.mipmap.ic_choose_li);
        } else {
            allSelect_img.setImageResource(R.mipmap.ic_choose_nor);
        }
        for (int i = 0; i < beanList.size(); i++) {
            beanList.get(i).setIsselect(isAllSelect);
            try {
                ImageView tv = (ImageView) swipe.getChildAt(i).findViewById(R.id.select);
                if (tv != null) {
                    tv.setImageResource(isAllSelect ? R.mipmap.ic_choose_li : R.mipmap.ic_choose_nor);
                }
            } catch (Exception e) {

            }
        }
        isAllSelect();
    }

    private void isAllSelect() {
        double nums = 0;
        double pricce = 0;

        double all = 0;
        isAllSelect = true;
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).isselect()) {
                nums = Integer.parseInt(beanList.get(i).getNum());
                /*try {
                    pricce = Double.parseDouble(beanList.get(i).getOprice()) * Double.parseDouble(MyApplication.getInstance().getUserBean().getRatio());
                } catch (Exception e) {*/
                    pricce = Double.parseDouble(beanList.get(i).getOprice());
//                }
                double prices = nums * pricce;
                all += prices;
            } else {
                isAllSelect = false;
            }

        }
        if (beanList.size() == 0)
            isAllSelect = false;

        DecimalFormat df = new DecimalFormat("######0.00");
        tv_all_price.setText(df.format(all));

        if (isAllSelect) {
            allSelect_img.setImageResource(R.mipmap.ic_choose_li);
        } else {
            allSelect_img.setImageResource(R.mipmap.ic_choose_nor);
        }
    }

    @Override
    public void onResume() {
        upload();
        isAllSelect();
        super.onResume();
    }


}
